package com.vcc.boss.core.interceptor;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.vcc.core.exception.PermissionException;
import com.vcc.data.entity.BossRolePermission;
import com.vcc.data.entity.BossUserPermission;
import com.vcc.data.entity.Permission;
import com.vcc.service.service.BossRolePermissionService;
import com.vcc.service.service.BossUserPermissionService;
import com.vcc.service.service.PermissionService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;

@Log4j2
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private PermissionService permissionService;
    @Resource
    private BossRolePermissionService bossRolePermissionService;
    @Resource
    private BossUserPermissionService bossUserPermissionService;
    @Resource
    private HttpServletRequest httpServletRequest;

    @Override
    public List<String> getPermissionList(Object o, String s) {
        List<BossRolePermission> bossRolePermissions = bossRolePermissionService.listByUserId(Long.valueOf(o.toString()));
        List<BossUserPermission> bossUserPermissions = bossUserPermissionService.listByUserId(Long.valueOf(o.toString()));
        List<Permission> permissionList = permissionService.list();
        HashSet<String> codes = new HashSet<>();
        List<String> list = bossRolePermissions.stream().map(it -> {
            Permission permission = permissionList.stream().filter(p -> p.getId().equals(it.getPermissionId())).findFirst().orElseThrow(() -> new PermissionException("解析权限发生错误"));
            if (it.getStatus().equals(0)) {
                return permission.getCode();
            } else {
                return "";
            }
        }).filter(it -> !Objects.equals(it, "")).distinct().toList();
        codes.addAll(list);
        codes.addAll(bossUserPermissions.stream().map(it -> {
            Permission permission = permissionList.stream().filter(p -> p.getId().equals(it.getPermissionId())).findFirst().orElseThrow(() -> new PermissionException("解析权限发生错误"));
            if (it.getStatus()) {
                return permission.getCode();
            } else {
                return "";
            }
        }).filter(it -> !Objects.equals(it, "")).distinct().toList());
        log.info("获取权限列表：{}", JSONUtil.toJsonStr(list));
        log.info("请求路径：{},请求用户：{}，请求来源：{}", httpServletRequest.getRequestURI(), o.toString(), httpServletRequest.getHeader("source"));
        return ListUtil.toList(codes);
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        return List.of();
    }
}
